function setDate(objEnddate, days){
    var dt = new Date(parseInt($dp.cal.getP('y')), parseInt($dp.cal.getP('M'))-1, parseInt($dp.cal.getP('d'))+days);
    objEnddate.value = dt.format("yyyy-MM-dd");
}

$(document).ready(function(){
	try{
		$.jgrid.no_legacy_api = true;
		$.jgrid.useJSON = true;
		$.jgrid.formatter.integer.thousandsSeparator = ',';
		$.jgrid.formatter.number.thousandsSeparator = ',';
		$.jgrid.formatter.currency.thousandsSeparator = ',';
		
		$("#orderItemsTable").jqGrid({						
			url : appRoot + '/quotationItem/list/' + bankStatementId + '?ajax=1',
			editurl : appRoot + '/quotationItem/save?ajax=1&quotationId=' + bankStatementId,
			datatype : 'json',
			mtype : 'GET',
			jsonreader: {             
				repeatitems: false,
				id:'Id',
				root:'rows'
			}, 
			colNames : [ 'id','objectId','款', '数量/款','单位','单价', '折扣价','总数量','总金额'], 
			colModel : [ 
	       {
				name : 'id',
				index : 'id',
				editable : true,
				hidden:true
				
			}, {
				name : 'objectId',
				index : 'objectId',
				editable : true,
				hidden:true
			},
			{
				name : 'title',
				index : 'title',
				width : 100,
				align : 'left',
				resizable : false,
				editable : true,
				edittype:'text',
				sortable: false,
				editrules : {
					 required : true,
		             number : true
				}

			}, {
	            name : 'quantity',
	            index : 'quantity',
	            width : 100,
	            align : 'right',
	            editable : true,
	            edittype:'text',
	            sortable: false,
	            editrules : {
	                required : true,
	                number : true
	            }                           
	        }, {
				name : 'unit',
				index : 'unit',
				width : 100,
				editable : true,
				edittype:'select',
				formatter:'select',
				editoptions : {
			        value :units
			    },
				editrules : {
					required : true
				}
			}, {
				name : 'unitPrice',
				index : 'unitPrice',
				width : 100,
				align : 'right',
				editable : true,
				edittype:'text',
				editrules : {
					 required : true,
		             number : true
				}
			}, {
				name : 'discountPrice',
				index : 'discountPrice',
				width : 100,
				editable : true,
				align : 'right',
				edittype:'text',
				sortable: false,
				editrules : {
					required : true,
					number : true
				}
			}, {
				name : 'totalQuantity',
				index : 'totalQuantity',
				align : 'right',
				width : 100,
				editable : false
			}, {
				name : 'total',
				index : 'total',
				width : 100,
				editable : false
			}
			],
			width: 730,
			height : 300,
			pager : $('#pager'),
			nowNum : 100,
			rowNum : 100,
			sortname : 'id',
			viewrecords : true,
			footerrow: true,
			shrinkToFit:false,
			caption : ''
		}).navGrid("#pager",{edit:true,add:true,del:true,search:false});

		
		$("#orderChargeTable1").jqGrid({                       
	        url : appRoot + '/quotationExtraItem/list/1/' + bankStatementId + '?ajax=1',
	        editurl : appRoot + '/quotationExtraItem/save?ajax=1&type=1&quotationId=' + bankStatementId,
	        datatype : 'json', 
	        mtype : 'GET',
	        jsonreader: {             
	            repeatitems: false,
	            id:'Id',
	            root:'rows'
	        }, 
	        colNames : [ 'id','objectId','Description', 'Cost'],
	        colModel : [
	       {
	            name : 'id',
	            index : 'id',
	            editable : true,
	            hidden:true
	            
	        }, {
	            name : 'objectId',
	            index : 'objectId',
	            editable : true,
	            hidden:true
	        },
	        {
	            name : 'description',
	            index : 'description',
	            width : 50,
	            align : 'left',
	            resizable : false,
	            editable : true,
	            edittype:'text',
	            sortable: false,
	            editrules : {
	                required : true
	            }

	        }, {
	            name : 'total',
	            index : 'total',
	            width : 40,
	            align : 'right',
	            editable : true,
	            sortable: false,
	            editrules : {
	            	required : true,
					number : true
	            }
	        }
	        ],
	        gridComplete: function(){
	            var grid = $("#orderChargeTable1");
	            var sumAmount = grid.jqGrid('getCol', 'amount', false, 'sum'); 
	            grid.jqGrid('footerData','set', {reason:"合计:", amount:sumAmount}); 
	        },
	        width: 730,
	        height : 100,
	        pager : $('#pager1'),
	        nowNum : 100,
	        rowNum : 100,
	        sortname : 'id',
	        viewrecords : true,
	        footerrow: true,
	        caption : 'Extra Cost'
	    }).navGrid("#pager1",{edit:true,add:true,del:true,search:false});
		
		$("#orderChargeTable2").jqGrid({                       
			 url : appRoot + '/quotationExtraItem/list/2/' + bankStatementId + '?ajax=1',
		        editurl : appRoot + '/quotationExtraItem/save?ajax=1&type=2&quotationId=' + bankStatementId,
	        datatype : 'json', 
	        mtype : 'GET',
	        jsonreader: {             
	            repeatitems: false,
	            id:'Id',
	            root:'rows'
	        }, 
	        colNames : [ 'id','objectId','Description', 'Cost'],
	        colModel : [
	       {
	            name : 'id',
	            index : 'id',
	            editable : true,
	            hidden:true
	            
	        }, {
	            name : 'objectId',
	            index : 'objectId',
	            editable : true,
	            hidden:true
	        },
	        {
	            name : 'description',
	            index : 'description',
	            width : 50,
	            align : 'left',
	            resizable : false,
	            editable : true,
	            edittype:'text',
	            sortable: false,
	            editrules : {
	                required : true
	            }

	        }, {
	            name : 'total',
	            index : 'total',
	            width : 40,
	            align : 'right',
	            editable : true,
	            sortable: false,
	            editrules : {
	            	required : true,
					number : true
	            }
	        }
	        ],
	        width: 730,
	        height : 100,
	        pager : $('#pager2'),
	        nowNum : 100,
	        rowNum : 100,
	        sortname : 'id',
	        viewrecords : true,
	        footerrow: true,
	        caption : 'Saving cost'
	    }).navGrid("#pager2",{edit:true,add:true,del:true,search:false});
		
	}catch(e){}
	
	$(".colorbox").colorbox({iframe:true, innerWidth:750, innerHeight:460});
	$(".picture").colorbox();

});

//page

function audit(orderId,action){
    $(".audit").attr("disabled",true);
    if(confirm("你确认正确？")){
    	$.ajax({
            url: appRoot + "/quotation/audit/" + orderId,
            type:'post',
            dataType:'json',
            data:"status=2" ,
            success:function(msg){
                if(msg.result){
                    window.location.href= appRoot + '/quotation/' + action +'?message=' + encodeURIComponent('操作成功');
                }else{
                    showMessage("操作失败");
                    $(".audit").attr("disabled",false);
                }
            }
       });
    }
}

function notify(){
    if(currentOrderId==null){
        return;
    }
    $(".audit").attr("disabled",true);
    $("#notifyButton").attr("disabled",true);
    var selected = getCheckedValuesString(document.getElementsByName("users"));
    var customer = ($("#customer_1").attr("checked")=="checked");
    var others = $("#otherUsers").val();
    if(!selected&&!customer&&!others){
        $("#suberror").html("请至少选择一个接收者").show();
        $(".audit").attr("disabled",false);
        $("#notifyButton").attr("disabled",false);
    }else{
        $("#suberror").hide();
        $("#subnotice").html("操作进行中...").show();
        $.ajax({
             url:appRoot + "/quotation/notify/" + currentOrderId + "?date=" + (new Date()).valueOf(),
             type:'post',
             dataType:'json',
             data:'purchasers=' + (selected==null?"":selected) + "&customer=" + customer + "&others=" + others,
             success:function(msg){
                 if(msg.result){
                     showMessage("邮件已发送");
                 }else{
                     showMessage("操作失败");
                 }
                 $(".audit").attr("disabled",false);
                 $("#notifyButton").attr("disabled",false);
                 jQuery.fn.colorbox.close();
             }
        });
    }
}

fileLimit = 4;
function createUploader(){
    var filelimituploader = new qq.FileUploader({
    element: $('#filelimit-fine-uploader')[0],
    action: appRoot + '/picture/upload/4/' + bankStatementId + '?ajax=1',
    debug: false,
    demoMode: false,
    forceMultipart:true,
    allowedExtensions: ['jpeg', 'jpg', 'gif', 'png'],
    sizeLimit: fileUploadSize,
    uploadButtonText:"上传图片",
    cancelButtonText:"取消",
    failUploadText:"上传失败",
    onSubmit: function(id, fileName) {
 	   orderfileCount ++;
        if(orderfileCount > fileLimit) {
            alert("已经达到最大上传文件数量，不能再上传了！");
            orderfileCount--;
            return false;
        }
    },
    onCancel: function(id, fileName) {
 	   orderfileCount--;
        if(orderfileCount <= fileLimit) {
            $('#filelimit-fine-uploader .qq-upload-button').show();
        }
    },
    onComplete: function(id, fileName, responseJSON) {
        if (responseJSON.success) {
            var fileId = responseJSON.fileId;
            var fileSuffix = responseJSON.fileSuffix;
            var fileName = responseJSON.fileName;
            $('#filelimit-fine-uploader').append('<div style="float: left;width: 200px;" id="d_f_' + fileId + '"><a href="' + appRoot + '/download/' 
                     + fileId + fileSuffix + '" title="' + fileName + '" class="picture"><img alt="' + fileName + '" src="' + appRoot + '/download/'
                     + fileId + fileSuffix + '" width="150">'
                     + '<a href="javascript:deletePicture(\'' + fileId + '\')">删除</a></div>');
            $(".picture").colorbox();
        }
    }
});
$(".qq-upload-list").hide();
}

function deletePicture(fileId){
    if(fileId){
        if(confirm("你确定要删除此图片吗？")){
        $.ajax({
             url: appRoot + "/picture/delete/" + fileId + "?ajax=1",
             type:'post',
             dataType:'json',
             success:function(msg){
                 if(msg.success){
                     alert("删除成功");
                     orderfileCount--;
                     $("#d_f_" + fileId).remove();
                     }
                 }
            });
        }
    }
}